﻿@using CID.Web.Support
@model CID.Web.Models.Development.ComponentViewModel

<div id="Tabs">
    <ul>
        <li><a href="#General">General</a></li>
        <li><a href="#ActivationParameters">Activation Parameters</a></li>
        <li><a href="#DeactivationParameters">Deactivation Parameters</a></li>
    </ul>
    <div id="General">
        @using (Html.BeginForm())
        {
            @Html.ValidationSummary(true)
            <div class="editor-label">
                @Html.LabelFor(model => model.Name)
            </div>
            <div class="editor-field">
                @Html.KOTextBoxFor(model => model.Name)
                @Html.ValidationMessageFor(model => model.Name)
            </div>

            <div class="editor-label">
                @Html.LabelFor(model => model.Description)
            </div>
            <div class="editor-field">
                @Html.KOTextAreaFor(model => model.Description)
                @Html.ValidationMessageFor(model => model.Description)
            </div>

            <div class="editor-label">
                @Html.LabelFor(model => model.RequiredServerRole)
            </div>
            <div class="editor-field">
                @Html.KODropDownListForEntity(m => m.RequiredServerRoleId, Model.AvailableServerRoles, Model.RequiredServerRoleId)
                @Html.ValidationMessageFor(model => model.RequiredServerRoleId)
            </div>

            <div class="editor-label">
                @Html.LabelFor(model => model.Responsible)
            </div>
            <div class="editor-field">
                @Html.KODropDownListForEntity(m => m.ResponsibleId, Model.AvailableUsers, Model.ResponsibleId)
                @Html.ValidationMessageFor(model => model.ResponsibleId)
            </div>

            <div class="editor-label">
                @Html.LabelFor(model => model.ActivationTemplate)
            </div>
            <div class="editor-field">
                @Html.KODropDownListForEntity(m => m.ActivationTemplateId, Model.AvailableActivationTemplates, Model.ActivationTemplateId, new { onchange = "javascript: OnActivationTemplateChanged(this);" })
                @Html.ValidationMessageFor(model => model.ActivationTemplateId)
            </div>

            <div class="editor-label">
                @Html.LabelFor(model => model.DeactivationTemplate)
            </div>
            <div class="editor-field">
                @Html.KODropDownListForEntity(m => m.DeactivationTemplateId, Model.AvailableDeactivationTemplates, Model.DeactivationTemplateId, new { onchange = "javascript: OnDeactivationTemplateChanged(this);" })
                @Html.ValidationMessageFor(model => model.DeactivationTemplateId)
            </div>

            <div class="editor-label">
                @Html.LabelFor(model => model.Enabled)
            </div>
            <div class="editor-field">
                @Html.KOCheckBoxFor(model => model.Enabled)
                @Html.ValidationMessageFor(model => model.Enabled)
            </div>

            @Html.HiddenFor(model => model.Id)
        }
    </div>
    <div id="ActivationParameters">
        @{ViewBag.EditorId = "ActivationParameterValues"; }
        @Html.Partial("ParameterValuesEditor")
    </div>
    <div id="DeactivationParameters">
        @{ViewBag.EditorId = "DeactivationParameterValues"; }
        @Html.Partial("ParameterValuesEditor")
    </div>

    <p>
        <!--TODO: this is not the best option, since is not using KO bindings, but is a hotfix for getting the button always visible. An alternative should be found-->
        <input type="button" value="Save" onclick="javascript: viewModel.Save();"/>
    </p>
</div>
<div>
    @if (Model.Id != 0)
    {
        @Html.ActionLink("Versions", "Versions", new { id=Model.Id })
        @Html.Raw("|")
    }
    @Html.ActionLink("Back to List", "Index")
</div>

@Html.Partial("ParameterValuesEditionHelper")

<script type="text/javascript">
    $(document).ready(function () {
        $("#Tabs").tabs({
            select: function (event, ui) { setTimeout(function () { $('.parameter-values-group').accordion('resize'); }, 10) }
        });
        viewModel.Load();

        if( viewModel.Id() == 0) {
            DisableActivationParametersTabs();
            DisableDeactivationParametersTabs();
        }

        ko.bindingHandlers.fadeVisible = new FadeVisibleHandler();
        ko.applyBindings(viewModel.ActivationParameterValuesList, document.getElementById("ActivationParameterValues"));
        ko.applyBindings(viewModel.DeactivationParameterValuesList, document.getElementById("DeactivationParameterValues"));
        ko.applyBindings(viewModel, document.getElementById("General"));
        $(".parameter-values-group").accordion( {fillSpace: true} );
    });


    function OnActivationTemplateChanged(source) {
        if(viewModel.Id() != 0)
        {
            var selectedTemplateId = source.options[source.selectedIndex].value;
            if(selectedTemplateId == viewModel.OriginalActivationTemplateId())
                EnableActivationParametersTabs();
            else 
                DisableActivationParametersTabs();
        }
    }

    function EnableActivationParametersTabs() {
        $("#Tabs").tabs("enable", 1);
    }

    function DisableActivationParametersTabs() {
        $("#Tabs").tabs("disable", 1);
    }

    function OnDeactivationTemplateChanged(source) {
        if(viewModel.Id() != 0)
        {
            var selectedTemplateId = source.options[source.selectedIndex].value;
            if(selectedTemplateId == viewModel.OriginalDeactivationTemplateId())
                EnableDeactivationParametersTabs();
            else 
                DisableDeactivationParametersTabs();
        }
    }

    function EnableDeactivationParametersTabs() {
        $("#Tabs").tabs("enable", 2);
    }

    function DisableDeactivationParametersTabs() {
        $("#Tabs").tabs("disable", 2);
    }

    var viewModel = {
        Id: ko.observable(),
        Name: ko.observable(),
        Description: ko.observable(),
        ResponsibleId: ko.observable(),
        RequiredServerRoleId: ko.observable(),
        Enabled: ko.observable(),
        OriginalActivationTemplateId: ko.observable(),
        ActivationTemplateId: ko.observable(),
        ActivationParameterValues: ko.observableArray([]),
        OriginalDeactivationTemplateId: ko.observable(),
        DeactivationTemplateId: ko.observable(),
        DeactivationParameterValues: ko.observableArray([]),
        Load: function () {
            var mapping = {
                'ActivationParameterValues': {
                    create: function (options) { return MapParameterValue(options); }
                },
                'DeactivationParameterValues': {
                    create: function (options) { return MapParameterValue(options); }
                }
            }
            ko.mapping.fromJS(@Html.JSON(Model), mapping, this);
            
            //When creating a new Version, there're no parameter values
            if(this.Id() == 0) {
                this.ActivationParameterValues = ko.observableArray([]); 
                this.DeactivationParameterValues = ko.observableArray([]); 
            }
            
            this.ActivationParameterValuesList = new ParameterValuesList(this.ActivationParameterValues());
            this.DeactivationParameterValuesList = new ParameterValuesList(this.DeactivationParameterValues());
            this.OriginalActivationTemplateId(this.ActivationTemplateId());
            this.OriginalDeactivationTemplateId(this.DeactivationTemplateId());
        },
        Save: function () {
            var viewModelJSON = ko.toJSON(ko.mapping.toJS(this));
            $.ajax({
                url: this.PostUrl(),
                data: viewModelJSON,
                type: 'POST',
                contentType: 'application/json;',
                dataType: 'json',
                success: function (response) {
                    debugger;
                    switch (response.Type) {
                        case "Redirect":
                            window.location.href = response.Url;
                            break;
                        case "View":
                            //TODO: display error in the summary error pane. Need to research how that's done with unobtrusive validation
                            alert(response.ModelError);
                            break;
                    }
                }
            });
        }
    };
</script>